import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Reply } from 'weaver-mobile-page';
import { withRouter } from 'react-router-dom';
import { Tools, List, Icon, Tree, SwipeAction } from 'weaver-mobile';
import { WrAlertPage} from "../../../../public";
import * as TaskMainApis from '../../../../api/task/taskMain';
const FormItem = List.FormItem
const getLabel = Tools.getLabel;

@inject("taskDetailSubtaskStore", "taskDetailStore", "taskCommonStore")
@withRouter
@observer
class Subtask extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            ...props
        }
    }

    componentWillMount() {
        const { sublist } = this.state.detail
        const { changeDatas } = this.props.taskDetailSubtaskStore

        let datas = []
        sublist.forEach((sub, i) => {
            datas.push(this.formatSubtaskToData(sub, 1))
        })
        changeDatas(datas)
    }

    componentWillReceiveProps(newProps) {
        const { changeDatas } = this.props.taskDetailSubtaskStore
        if (newProps.detail != this.state.detail) {
            this.setState({
                detail: newProps.detail
            })
            if (newProps.detail) {
                let datas = []
                newProps.detail.sublist.forEach((sub, i) => {
                    datas.push(this.formatSubtaskToData(sub, 1))
                })
                changeDatas(datas)
            }
        }
    }

    componentWillUnmount() {

    }

    onItemClick = (taskid, event) => {
        const { changeTaskid, changeTaskDetail } = this.props.taskDetailStore
        event.preventDefault()
        event.stopPropagation()
        // this.props.history.replace("/taskHome/taskDetail/" + taskid)
        // changeTaskid(taskid)
        // changeTaskDetail({})
        window.openAppLink(null, taskid, "wrltask", null, null)
    }

    formatSubtaskToData = (subtask, deep) => {
        return {
            deep,
            haschild: subtask.childcount !== 0 && subtask.childcount !== "" && parseInt(subtask.childcount + "") > 0,
            isopen: false,
            key: subtask.key,
            name: <span className="title" style={{ width: window.innerWidth - (14 * deep + 24 + 65) }} onClick={(event) => this.onItemClick(subtask.key, event)}>{subtask.title}</span>,
            extra: <span className="right-info" onClick={(event) => this.onItemClick(subtask.key, event)}>{subtask.rightData.length > 0 ? subtask.rightData[0].name : ''}</span>
        }
    }

    onFastAddSubtask = (taskinfoDatas) => {
        const { taskDetail, changeTaskDetail } = this.props.taskDetailStore
        const { reply, datas, changeDatas } = this.props.taskDetailSubtaskStore
        const { taskid } = this.state
        reply.doClear()

        let content = taskinfoDatas.text.replace(new RegExp(/<\/?[a-z]+>/img), "")
        if (content.trim() == "" || content.trim() == "null") {
            this.props.taskCommonStore.warn(getLabel(504646, '任务名称不能为空'))
            return
        }
        TaskMainApis.addTask({
            taskName: content,
            parentid: taskid,
            mainpage: 1,
            relateadd: 1
        }).then(res => {
            if (res.status === "1") {
                let newsubdatas = []
                res.subdatas.forEach((sub, i) => {
                    newsubdatas.push(this.formatSubtaskToData(sub, 1))
                })
                changeDatas([...datas, ...newsubdatas])
                changeTaskDetail({ ...taskDetail, sublist: [...taskDetail.sublist, ...res.subdatas] })
            }
        })
    }

    onAddSubtask = (nodeinfo) => {
        const parentTaskid = nodeinfo._owner.key
        this.props.history.push("/taskHome/newTask?parentid=" + parentTaskid)
    }

    render() {
        const { detail } = this.state
        const { reply, datas, changeDatas } = this.props.taskDetailSubtaskStore

        return (
            <div className="workrelate-mobile-task-subtask-wrapper">
                <div className="content-wrapper">
                    {
                        datas.length > 0 ?
                            <Tree
                                async
                                onAsyncSelect={node => new Promise((resolve) => {
                                    const taskid = node.key
                                    TaskMainApis.getChildTaskList({
                                        taskid: taskid,
                                        sorttype: "4"
                                    }).then(res => {
                                        let childrenData = []
                                        res.datas.forEach((sub, i) => {
                                            childrenData.push(this.formatSubtaskToData(sub, node.deep + 1))
                                        })
                                        resolve(childrenData)
                                    })
                                })}
                                datas={toJS(datas)}
                                rowKey="key"
                                checkable={0}
                                decorator={content => (
                                    <SwipeAction
                                        autoClose
                                        right={detail.cancreate ? [
                                            {
                                                text: getLabel(83924,'新建子任务'),
                                                onPress: () => this.onAddSubtask(content),
                                                style: { backgroundColor: '#4D7AD8 ', color: 'white', fontFamily: "PingFang-SC-Medium", fontSize: "14*@hd", padding: "0 10px" }
                                            }
                                        ]: []}
                                    >
                                        {content}
                                    </SwipeAction>
                                )}
                                // onExpanded={(...arg) => { console.log(arg) }}
                                onChange={data => changeDatas(data)}
                            />
                            :
                            <WrAlertPage show={true} msg={getLabel(513865,'暂无下级')} icon={"no-data"} top="35%"/>
                    }
                </div>

                {
                    detail.cancreate &&
                    <div className="bottom-wrapper">
                        <Reply.NoMask
                            wrappedComponentRef={ref => this.replyRef = ref} // 由于react升级，ref={ref => this.replyRef = ref} 这种方式不能用了，这里取ref请按照目前给的这个方式
                            store={reply}
                            showTabBar={false}
                            showOutInput={false}
                            showOutTabBar={false}
                            placeholder={getLabel('521216','请输入子任务名称') }
                            onSubmit={datas => this.onFastAddSubtask(toJS(datas))} // 提交的时候，如果需要清空数据，调用store的doClear方法
                        />
                    </div>
                }
            </div>
        )
    }
}

export default Subtask
